﻿using System;
using System.Configuration;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using EmbeddedSharp.Core;
using System.IO;
using LibUnitConverter;
using System.Collections;
using System.Collections.Generic;

namespace Zove.Desktop {
    public partial class PreferencesForm : Form {
        private string CONFIG_DEFAULTWS = "Default Workspace";

        public void SaveScriptingSettings() {
            if (Convert.ToInt32(
                this.tbPrecision.Text) < 0) {
                MessageBox.Show("Precision cannot be negatvie.");
                return;
            }

            DesktopUtils.Precision = this.tbPrecision.Text;
            StringBuilder path = new StringBuilder();

            path = new StringBuilder();
            //foreach (DataGridViewRow r in this.gvFunctionLibraries.Rows) {
            //    if (r.Cells["ColLibraryPath"].Value == null) {
            //        continue;
            //    }

            //    path.AppendLine(r.Cells["ColLibraryPath"].Value.ToString()).Append(";");
            //}
            //path.Remove(path.Length - 1, 1);

            //DesktopUtils.FunctionPath = path.ToString();
        }

        public PreferencesForm() {
            InitializeComponent();

            this.Load += new EventHandler(PreferencesForm_Load);
        }

        /// <summary>
        /// Load workspace settings
        /// </summary>
        private void LoadWorkspaceTab() {
            string[] ext = DesktopUtils.Extensions.Split(';');
            foreach (string extension in ext) {
                this.cbExtension.Items.Add(extension);
            }

            string[] m = DesktopUtils.ModelPool.Split(';');
            foreach (string x in m) {
                this.lbModelLibraries.Items.Add(x);
            }

            this.tbDefaultWorkspace.Text = ConfigurationManager.AppSettings[CONFIG_DEFAULTWS];
            cbLN.Checked = DesktopFormContext.Context.ShowLineNumber;
        }

        private void LoadProgrammingTab() {
            this.tbPrecision.Text = Utils.Precision.ToString();

            if (File.Exists(DesktopUtils.ConstantFile)) {
                string[] lines = System.IO.File.ReadAllLines(
                    DesktopUtils.ConstantFile, Encoding.UTF8);
                foreach (string ln in lines) {
                    string[] p = ln.Split('=');
                    //gvConstants.Rows.Add(p[0], p[1]);
                }
            }

            string[] classPath = Utils.FunctionPath.Split(';');
            foreach (string cp in classPath) {
                //this.gvFunctionLibraries.Rows.Add(cp);
            }
        }

        private const string CONFIG_MODELLIBRARIES = "Model Libraries";

        private DefaultUnitConverter unitConv = new DefaultUnitConverter();

        private void LoadModellingTab() {
            string modelLibraries = ConfigurationManager.AppSettings[CONFIG_MODELLIBRARIES];

            if (!string.IsNullOrEmpty(modelLibraries)) {
                string[] libraries = modelLibraries.Split(';');

                this.lbModelLibraries.DataSource = libraries;
            }

            List<string> catalog = new List<string>();
            foreach (object c in unitConv.Catalogs) {
                catalog.Add(c.ToString());
            }

            this.cbUnitCatalog.DataSource = catalog;
            this.cbUnitCatalog.TextChanged += new EventHandler(cbUnitCatalog_TextChanged);
        }

        public void cbUnitCatalog_TextChanged(object sender, EventArgs e) {
            List<UnitData> data = unitConv.GetUnits(this.cbUnitCatalog.SelectedItem.ToString());
            this.gvUnitData.DataSource = data;
        }

        public const string CONFIG_QUERYLAYOUT = "query layout";

        private void LoadQueryingTab() {
            string layout = ConfigurationManager.AppSettings[CONFIG_QUERYLAYOUT];

            if (!string.IsNullOrEmpty(layout)) {
                this.cbQueryLayout.SelectedItem = layout;
            }
        }

        public void PreferencesForm_Load(object sender, EventArgs e) {
            this.LoadWorkspaceTab();
            this.LoadProgrammingTab();
            this.LoadModellingTab();
            this.LoadQueryingTab();
        }

        private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e) {
        }

        private void button1_Click(object sender, EventArgs e) {
            button2_Click(sender, e);
            this.Close();
        }

        private void btnCancel_Click(object sender, EventArgs e) {
            this.Close();
        }

        public void SaveQueryingTabSettings() {
            ConfigurationManager.AppSettings[CONFIG_QUERYLAYOUT] = this.cbQueryLayout.SelectedItem.ToString();
        }

        private void button2_Click(object sender, EventArgs e) {
            SaveScriptingSettings();

            SaveWorkspaceSettings();

            SaveModellingSettings();

            SaveQueryingTabSettings();
        }

        private void SaveWorkspaceSettings() {
            StringBuilder b = new StringBuilder();
            for (int index = 0; index < this.cbExtension.Items.Count; index++) {
                b.Append(this.cbExtension.Items[index].ToString());
                if (index + 1 < this.cbExtension.Items.Count) {
                    b.Append(";");
                }
            }
            DesktopUtils.Extensions = b.ToString();

            if (font != null) {
                UpdateFontSettings(font);
                DesktopUtils.Font = font.Name;
                DesktopUtils.FontSize = font.Size;
                DesktopFormContext.Context.Font = font;
            }

            if (this.cbLN.Checked
                != DesktopFormContext.Context.ShowLineNumber) {
                UpdateShowLineNumber(this.cbLN.Checked);
                DesktopFormContext.Context.ShowLineNumber
                    = this.cbLN.Checked;
            }
        }

        private void SaveModellingSettings() {
            StringBuilder libraries = new StringBuilder();
            foreach (object obj in this.lbModelLibraries.Items) {
                libraries.Append(obj.ToString()).Append(";");
            }

            DesktopUtils.ModelPool = libraries.ToString();
        }

        private Font font = null;

        private void button3_Click(object sender, EventArgs e) {
            FontDialog d = new FontDialog();
            d.Font = DesktopFormContext.Context.Font;

            if (d.ShowDialog() == DialogResult.OK) {
                font = d.Font;
            }
        }

        public void UpdateFontSettings(Font font) {
            foreach (Form f in DesktopFormContext.Context.Values) {
                if (f.GetType().Equals(typeof(EditingForm))) {
                    EditingForm ef = (EditingForm)f;

                    ef.Font = font;
                }
            }
        }

        public void UpdateShowLineNumber(bool show) {
            foreach (Form f in DesktopFormContext.Context.Values) {
                if (f.GetType().Equals(typeof(EditingForm))) {
                    EditingForm ef = (EditingForm)f;

                    ef.LineNumberVisible = show;
                }
            }
        }

        private void btnAddFilter_Click(object sender, EventArgs e) {
            if (!string.IsNullOrEmpty(this.tbFileExtension.Text)) {
                this.cbExtension.Items.Add(this.tbFileExtension.Text);
            }
        }

        private void btnDeleteFilter_Click(object sender, EventArgs e) {
            this.cbExtension.Items.Remove(this.cbExtension.SelectedItem);
        }

        private void btnOpen_Click(object sender, EventArgs e) {
            FolderBrowserDialog d = new FolderBrowserDialog();

            if (d.ShowDialog() == DialogResult.OK) {
                this.tbDefaultWorkspace.Text = d.SelectedPath;
            }
        }

        private void tableLayoutPanel1_Paint(object sender, PaintEventArgs e) {

        }

        private void btnRemove_Click(object sender, EventArgs e) {
            foreach (object obj in this.lbModelLibraries.SelectedItems) {
                this.lbModelLibraries.Items.Remove(obj);
            }
        }

        private void btnBrowse_Click(object sender, EventArgs e) {
            FolderBrowserDialog d = new FolderBrowserDialog();

            if (d.ShowDialog() == DialogResult.OK) {
                this.tbDefaultWorkspace.Text = d.SelectedPath;
            }
        }

        private void btnAddModelLibrary_Click(object sender, EventArgs e) {
            FolderBrowserDialog d = new FolderBrowserDialog();

            if (d.ShowDialog() == DialogResult.OK) {
                string path = d.SelectedPath;
                if (!string.IsNullOrEmpty(path)
                    && Directory.Exists(path)
                    && !this.lbModelLibraries.Items.Contains(path)) {
                    this.lbModelLibraries.Items.Add(path);
                }
            }
        }

        private void btnAddFunctionLibrary_Click(object sender, EventArgs e) {
            OpenFileDialog d = new OpenFileDialog();

            d.Filter = "DLL & EXE (*.dll, *.exe) |*.dll";
            if (d.ShowDialog() == DialogResult.OK) {
                this.lbLibraries.Items.Add(d.FileName);
            }
        }

        private void btnRemoveFunctionLibrary_Click(object sender, EventArgs e) {
            this.lbLibraries.Items.Remove(this.lbLibraries.SelectedIndex);
        }

        private void cbUnitCatalog_SelectedIndexChanged(object sender, EventArgs e) {

        }
    }
}
